﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using MOMKeLABS.ServiceReference;
using System.Windows.Browser;

namespace MOMKeLABS
{
    public partial class MainPage : UserControl
    {
        /// <summary>
        /// The service client used for the authetnication in this class
        /// </summary>
        private ServiceClient Svc
        {
            get;
            set;
        }

        public MainPage()
        {
            InitializeComponent();

        }

        /// <summary>
        /// adds a widnow to the desktop
        /// </summary>
        /// <param name="w"></param>
        public void AddWindow(MOMKeLABS.Controls.Window.Window w)
        {
            Desktop.Children.Add(w);
        }

        /// <summary>
        /// removes a window from the desktop
        /// </summary>
        /// <param name="w"></param>
        public void RemoveWindow(MOMKeLABS.Controls.Window.Window w)
        {

            int z = (int)w.GetValue(Canvas.ZIndexProperty);

            foreach (UIElement win in Desktop.Children)
            {

                if (win.GetType() != typeof(Controls.Window.Window))
                    continue;

                int dz = (int)win.GetValue(Canvas.ZIndexProperty);


                if (dz <= z)
                {
                    win.SetValue(Canvas.ZIndexProperty, dz - 1);
                }
            }

            MinmizeWindowContainer.Children.Remove(w.MinWin);
            Desktop.Children.Remove(w);
        }


        public void BringWindowToFront(MOMKeLABS.Controls.Window.Window w)
        {
            foreach (UIElement win in Desktop.Children)
            {

                if (win.GetType() != typeof(Controls.Window.Window))
                    continue;

                if (w == win)
                {
                    w.SetValue(Canvas.ZIndexProperty, Desktop.Children.Count);
                    continue;
                }

                int z = (int)win.GetValue(Canvas.ZIndexProperty);

                if (z > 0)
                {
                    win.SetValue(Canvas.ZIndexProperty, z - 1);
                }



            }
            
        }
  

        /* START TEST CODE */

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ((((sender as Button).Parent as Border).Parent as Grid).Parent as MOMKeLABS.Controls.Window.Window).SetValue(Canvas.ZIndexProperty, 3);

           
        }

        /* END TEST CODE */


        /// <summary>
        /// Open the start menu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void StartButtonGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
  
        //}

        //private void StartButtonGrid_MouseEnter(object sender, MouseEventArgs e)
        //{
        //    StartButtonGrid.Background = App.Current.Resources["StartButton_hover"] as ImageBrush;
        //}

        //private void StartButtonGrid_MouseLeave(object sender, MouseEventArgs e)
        //{
        //    StartButtonGrid.Background = App.Current.Resources["StartButton"] as ImageBrush;
        //}

        public void CloseAllPopupWindows()
        {
            List<Controls.Popup.ContextPopupContainer> toBeRemoved = new List<Controls.Popup.ContextPopupContainer>();

            foreach (UIElement el in this.Desktop.Children)
            {
                if (el.GetType() == typeof(Controls.Popup.ContextPopupContainer))
                {
                    toBeRemoved.Add((el as Controls.Popup.ContextPopupContainer));
                }
            }

            foreach (Controls.Popup.ContextPopupContainer c in toBeRemoved)
            {
                this.Desktop.Children.Remove(c);
            }

            toBeRemoved = null;
        }

        /// <summary>
        /// called when ever a left button event is fired somewhere to remove all the popups
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            CloseAllPopupWindows();
        }


        /// <summary>
        /// handle all the right click events for opening the popups
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            // don't bubble the event back up to the silverlight framework
            e.Handled = true;

            // firstly close all other popups
            CloseAllPopupWindows();

            // decide on which popup should be opened

            switch (e.OriginalSource.GetType().ToString())
            {
                case "System.Window.Grid":

                    switch((e.OriginalSource as Grid).Name)
                    {



                        default:
                            CloseAllPopupWindows();
                            break;
                    }

                    break;

                case "System.Windows.Controls.Image":

                    Controls.Popup.ContextPopupContainer c = new Controls.Popup.ContextPopupContainer();

                    c.LayoutRoot.Children.Add(new Controls.Popup.MinimizedWindowContextMenu()
                        {
                            ParentWindow = ((e.OriginalSource as Image).Tag as Controls.Window.Window)
                        });

                        c.Show(e.GetPosition(null).Y, e.GetPosition(null).X);

                    break;

                default:
                    // just close all the others
                    CloseAllPopupWindows();
                    break;
            }

        }

        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            CloseAllPopupWindows();

            Controls.Popup.ContextPopupContainer c = new Controls.Popup.ContextPopupContainer();

            c.LayoutRoot.Children.Add(new Controls.Popup.StartMenu());

            c.Show(Desktop.ActualHeight, 0);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            // get the user settings class
            this.Svc = Security.Authentication.Connect();

            if ((App.Current as App).User == null)
            {
                // send the off to the login window
                HtmlPage.Window.Navigate(new Uri(Constants.ApplicationConstants.GetLoginURL(), UriKind.Absolute));
            }

            this.Svc.GetUserSettingsCompleted += new EventHandler<GetUserSettingsCompletedEventArgs>(Svc_GetUserSettingsCompleted);

            this.Svc.GetUserSettingsAsync((App.Current as App).User.Email);
        }

        /// <summary>
        /// handle the user settings response form the server
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Svc_GetUserSettingsCompleted(object sender, GetUserSettingsCompletedEventArgs e)
        {
            if(e.Error != null || e.Result == null || (App.Current as App).User == null)
            {
                MessageBox.Show("Some where along the way your user settings got lost. Try logging in again to see if they turn up");
                return;
            }

            // save their settings
            (App.Current as App).User.Settings = e.Result; 

        }


   }
}
